#include "widget.h"
#include "ui_widget.h"
#include <QUrl>
#include <QUrlQuery>
#include <QNetworkRequest>
#include <QBuffer>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QFileDialog>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //创建客户端
    client = new QNetworkAccessManager(this);
    //客户端收到服务器响应消息后调用槽函数
    connect(client, &QNetworkAccessManager::finished, this, &Widget::on_reply);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_openButton_clicked()
{
    //读取图像文件
    QPixmap pixmap(ui->fileEdit->text());
    //将图像缩放到Label控件大小，并保持原始比例
    pixmap = pixmap.scaled(ui->pixmapLabel->size(), Qt::KeepAspectRatio);
    //显示图像
    ui->pixmapLabel->setPixmap(pixmap);
}

void Widget::on_browseButton_clicked()
{
    //打开选择文件对话框
    QString name = QFileDialog::getOpenFileName(this);
    ui->fileEdit->setText(name);
}

void Widget::on_requestButton_clicked()
{
    //通用物体识别
    QUrl url("https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general");

    //设置URL参数
    QUrlQuery query;
    query.addQueryItem("access_token", ui->tokenEdit->text());
    url.setQuery(query);

    //构造请求消息
    QNetworkRequest request(url);
    request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");

    //获取打开的图片并转码（base64+urlencoding）
    QBuffer buf;
    buf.open(QIODevice::WriteOnly);
    ui->pixmapLabel->pixmap(Qt::ReturnByValue).save(&buf, "JPG");
    QByteArray base64 = buf.data().toBase64().toPercentEncoding();
    buf.close();

    //生成表单参数
    QUrlQuery body;
    body.addQueryItem("image", QString(base64));

    //发送请求消息
    client->post(request, body.toString().toUtf8());
}

void Widget::on_reply(QNetworkReply* reply)
{
    //接收响应消息并解析
    QJsonObject root = QJsonDocument::fromJson(reply->readAll()).object();
    //获取第一个结果
    ui->resultLabel->setText(root["result"].toArray().first()["keyword"].toString());
    reply->deleteLater();
}
